"""
Application Configuration
Environment-aware settings management
"""

from functools import lru_cache
from typing import List
from pydantic import validator
from pydantic_settings import BaseSettings
import os


class Settings(BaseSettings):
    """Application settings"""

    # Environment
    ENVIRONMENT: str = "development"
    DEBUG: bool = True

    # Server
    HOST: str = "0.0.0.0"
    PORT: int = 8000

    # Database - 统一数据库
    UNIFIED_DB_PATH: str = "./data/uma_insight.db"

    # Security
    SECRET_KEY: str
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30

    # CORS
    ALLOWED_HOSTS: List[str] = [
        "http://localhost:3000",
        "http://127.0.0.1:3000",
        "http://localhost:3001",
        "http://127.0.0.1:3001",
        "http://localhost:3002",
        "http://127.0.0.1:3002"
    ]

    @validator("UNIFIED_DB_PATH", pre=True)
    def resolve_db_path(cls, v):
        """Resolve relative database path to absolute path"""
        if not os.path.isabs(v):
            return os.path.abspath(os.path.join(os.path.dirname(__file__), "../../..", v))
        return v

    @validator("DEBUG", pre=True)
    def set_debug_from_env(cls, v):
        """Set debug based on environment"""
        if os.getenv("ENVIRONMENT") == "production":
            return False
        return v

    class Config:
        env_file = ".env"
        case_sensitive = True
        extra = "ignore"


@lru_cache()
def get_settings() -> Settings:
    """Get cached settings instance"""
    return Settings()


settings = get_settings()